package com.ylyq.ylxx.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylyq.ylxx.constants.AccountConstant;
import com.ylyq.ylxx.context.FilterContextHandler;
import com.ylyq.ylxx.entity.*;
import com.ylyq.ylxx.lingo.ILingoService;
import com.ylyq.ylxx.lingo.ResultCore;
import com.ylyq.ylxx.mapper.YlyqCoreTagMapper;
import com.ylyq.ylxx.mapper.YlyqCreativeTitleV2Mapper;
import com.ylyq.ylxx.model.ResponseData;
import com.ylyq.ylxx.model.bean.*;
import com.ylyq.ylxx.model.request.*;
import com.ylyq.ylxx.service.*;
import com.ylyq.ylxx.util.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ini4j.Wini;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @ClassName IOceaneginePlanServiceImpl
 * @Description TODO
 * @Author xiaweichao
 * @Date 2020/6/28 15:43
 * @Version 1.0
 */
@Slf4j
@Service
public class OceaneginePlanServiceImpl implements IOceaneginePlanService {
    @Value("${public.config.python.pythonPath}")
    private String pythonPath;
    @Value("${public.config.python.pythonSuffix}")
    private String pythonSuffix;
    @Autowired
    private ILingoService iLingoService;
    @Autowired
    private YlyqCoreTagMapper ylyqCoreTagMapper;
    @Autowired
    private IYlyqBudgetService iYlyqBudgetService;
    @Autowired
    private IYlyqTypeProductService iYlyqTypeProductService;
    @Autowired
    private IOceanengineToolService iOceanengineToolService;
    @Autowired
    private IYlyqCityService iYlyqCityService;
    @Autowired
    private IYlyqAreaOceangineService iYlyqAreaOceangineService;
    @Autowired
    private IYlyqCreativeTagService iYlyqCreativeTagService;
    @Autowired
    private IYlyqCreativeTitleService iYlyqCreativeTitleService;
    @Autowired
    private IYlyqCreativeAcitonService iYlyqCreativeAcitonService;
    @Autowired
    private IYlyqCreativeTitleV2Service iYlyqCreativeTitleV2Service;
    @Autowired
    private YlyqCreativeTitleV2Mapper ylyqCreativeTitleV2Mapper;
    @Autowired
    private IYlyqCreativeVideoMaterialService iYlyqCreativeVideoMaterialService;
    @Autowired
    private IYlyqConvertUrlService iYlyqConvertUrlService;
    @Autowired
    private IOceanegineReportService iOceanegineReportService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public OceanenginePlanInfo getPlan(GetPlanInfoRequest getPlanInfoRequest) {

        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "ad/get/";

        // 构造请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(getPlanInfoRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanenginePlanInfo oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanenginePlanInfo.class);
        if (jsonObject != null) {
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
            if (jsonArray != null)
                for (int i = 0; i < jsonArray.size(); i++) {
                    if (StringUtils.isNotBlank(jsonArray.getJSONObject(i).getString("package")))
                        oceanengineAccount.getData().getList().get(i).setPackage_(jsonArray.getJSONObject(i).getString("package"));

                    JSONArray jsonArray1 = jsonArray.getJSONObject(i).getJSONObject("audience").getJSONArray("geolocation");
                    for (int j = 0; j < jsonArray1.size(); j++) {
                        if (null != jsonArray1.getJSONObject(j).getFloat("long")) {
                            oceanengineAccount.getData().getList().get(i).getAudience().getGeolocation().get(j).setLong_(jsonArray1.getJSONObject(j).getFloat("long"));
                        }
                    }
                }
        }
        return oceanengineAccount;
    }

    @Override
    public ResponseData getPlanAndReport(GetPlanInfoRequest getPlanInfoRequest) {
        try {
            OceanenginePlanInfo oceanenginePlanInfo = getPlan(getPlanInfoRequest);
            List<OceanenginePlanInfo.DataBean.ListBean> list = oceanenginePlanInfo.getData().getList();
            if (null != list)
                for (OceanenginePlanInfo.DataBean.ListBean temp : list) {

                    GetReportPlanRequest getReportPlanRequest = new GetReportPlanRequest();
                    getReportPlanRequest.setAdvertiser_id(getPlanInfoRequest.getAdvertiser_id());
                    getReportPlanRequest.setStart_date(getPlanInfoRequest.getReportFiltering().getStart_date());
                    getReportPlanRequest.setEnd_date(getPlanInfoRequest.getReportFiltering().getEnd_date());

                    GetReportPlanRequest.FilteringGetReportPlanRequest filtering = new GetReportPlanRequest.FilteringGetReportPlanRequest();
                    filtering.setCampaign_ids(new Long[]{temp.getId()});
                    getReportPlanRequest.setFiltering(filtering);
                    getReportPlanRequest.setGroup_by(new String[]{"STAT_GROUP_BY_FIELD_ID"});


                    OceanengineReportPlanInfo reportGroup = iOceanegineReportService.getReportPlan(getReportPlanRequest);

                    if (null != reportGroup && null != reportGroup.getData().getList() && !reportGroup.getData().getList().isEmpty())
                        temp.setReportdetail(reportGroup.getData().getList().get(0));
                }

            return new ResponseData(ResponseData.Result.SUCCESS, oceanenginePlanInfo);
        } catch (Exception e) {
            return new ResponseData(ResponseData.Result.NODATA);
        }
    }

    @Override
    public OceanengineCreatePlanResult createPlan(CreatePlanInfoRequest createPlanInfoRequest) {

        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "ad/create/";

        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSON(createPlanInfoRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineCreatePlanResult oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineCreatePlanResult.class);
        return oceanengineAccount;
    }

    @Override
    public OceanengineUpdatePlanResult updatePlan(UpdatePlanInfoRequest createPlanInfoRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "ad/update/";


        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSON(createPlanInfoRequest).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineUpdatePlanResult oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUpdatePlanResult.class);
        return oceanengineAccount;
    }

    @Override
    public OceanengineUpdatePlanStateResult updateBatchPlanState(UpdatePlanStateInfoRequest updatePlanInfoRequests) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "ad/update/status/";

        // 请求参数
        Map<String, Object> data = new HashMap();
        if (updatePlanInfoRequests.getAdvertiser_id() != null)
            data.put("advertiser_id", updatePlanInfoRequests.getAdvertiser_id());
        if (updatePlanInfoRequests.getAd_ids() != null)
            data.put("ad_ids", updatePlanInfoRequests.getAd_ids());
        if (StringUtils.isNotBlank(updatePlanInfoRequests.getOpt_status()))
            data.put("opt_status", updatePlanInfoRequests.getOpt_status());


        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSONString(data), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineUpdatePlanStateResult oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUpdatePlanStateResult.class);
        return oceanengineAccount;
    }

    @Override
    public OceanengineUpdatePlanBudgetResult updateBatchPlanBudget(UpdatePlanBudgetInfoRequest updatePlanInfoRequests) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "ad/update/budget/";

        // 请求参数
        Map<String, Object> data = new HashMap();
        if (updatePlanInfoRequests.getAdvertiser_id() != null)
            data.put("advertiser_id", updatePlanInfoRequests.getAdvertiser_id());
        if (updatePlanInfoRequests.getData() != null) {
            data.put("data", updatePlanInfoRequests.getData());
        }


        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSONString(data), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineUpdatePlanBudgetResult oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUpdatePlanBudgetResult.class);
        return oceanengineAccount;
    }

    @Override
    public OceanengineUpdatePlanBidResult updateBatchPlanBid(UpdatePlanBidInfoRequest updatePlanBidInfoRequest) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "ad/update/bid/";

        // 请求参数
        Map<String, Object> data = new HashMap();
        if (updatePlanBidInfoRequest.getAdvertiser_id() != null)
            data.put("advertiser_id", updatePlanBidInfoRequest.getAdvertiser_id());
        if (updatePlanBidInfoRequest.getData() != null) {
            data.put("data", updatePlanBidInfoRequest.getData());
        }


        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.post(open_api_url_prefix + uri, JSONObject.toJSONString(data), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineUpdatePlanBidResult oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineUpdatePlanBidResult.class);
        return oceanengineAccount;
    }

    @Override
    public OceanengineRejectReasonResult getRejectReason(GetRejectReasonRequest getRejectReason) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.OCEANENGINE_URL + "2/";
        String uri = "ad/reject_reason/";

        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", FilterContextHandler.getOceaneToken());

        String result = HttpClientUtils.get(open_api_url_prefix + uri, JSONObject.toJSON(getRejectReason).toString(), headers);

        JSONObject jsonObject = JSONObject.parseObject(result);
        OceanengineRejectReasonResult oceanengineAccount = JSONObject.toJavaObject(jsonObject, OceanengineRejectReasonResult.class);
        return oceanengineAccount;
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)//加上事务后，上传的视频素材不能立马保存到数据库，而现在场景需要立马保存立马使用
    public ResponseData generatePlans(GeneratePlansRequest generatePlansRequest) throws Exception {

        log.info("生成计划start======");
        if(generatePlansRequest.getPlanCount()==null){
            generatePlansRequest.setPlanCount(3);
        }

//        String groupName = "销售线索收集_" + Tools.getCurrentDate("yyyyMMdd_HH:mm");
        String groupName = generatePlansRequest.getProductName() + Tools.getCurrentDate("yyyyMMdd_HH:mm");

        final CountDownLatch latch = new CountDownLatch(2);

        final String[] productResult = new String[1];
        final String[] planCoreResult = new String[1];
        final List<YlyqCoreTag>[] ylyqCoreTags = new List[]{new ArrayList<>()};

        ExecutorService cachedThreadPool = Executors.newFixedThreadPool(2);
        cachedThreadPool.execute(new Runnable() {
            public void run() {

                /**
                 * @Author xiaweichao
                 * @Description //TODO 获取产品打分  * @Date 14:34 2020/7/23
                 * @Param [generatePlansRequest]
                 * @return com.ylyq.ylxx.model.ResponseData
                 **/
                try {
                    log.info("获取产品打分线程开始");
                    StringBuilder parms = new StringBuilder();
                    parms.append(generatePlansRequest.getCategory_id() + "~\n");
                    parms.append(generatePlansRequest.getBrand_id() + "~\n");

                    //产品定价 高 高中 中端 中低 低
                    if (generatePlansRequest.getPrice() >= 1.5 * generatePlansRequest.getPrice_avg()) {
                        parms.append("1~\n");
                    } else if (generatePlansRequest.getPrice() >= 1.2 * generatePlansRequest.getPrice_avg()) {
                        parms.append("2~\n");
                    } else if (generatePlansRequest.getPrice() >= 0.8 * generatePlansRequest.getPrice_avg()) {
                        parms.append("3~\n");
                    } else if (generatePlansRequest.getPrice() >= 0.5 * generatePlansRequest.getPrice_avg()) {
                        parms.append("4~\n");
                    } else {
                        parms.append("5~\n");
                    }
                    //获取产品打分值
//                String path = ResourceUtils.getURL("classpath:").getPath().replace("/target/classes", "") + "\\src\\main\\resources\\lingo\\lingoproduct.lng";
//                String path = System.getProperty("user.dir")+ "\\ylyq\\src\\main\\resources\\lingo\\lingoproduct.lng";
                    QueryWrapper<YlyqTypeProduct> queryWrapper = new QueryWrapper<>();
                    queryWrapper.select("product_flag");
                    queryWrapper.eq("product_name", generatePlansRequest.getProductName());
                    List<Object> productNames = iYlyqTypeProductService.listObjs(queryWrapper);
                    if (productNames != null && !productNames.isEmpty())
                        parms.append(productNames.get(0).toString());
                    String path = "lingo/lingoproduct.lng";
                    File resultFile = iLingoService.excuteLingo(parms.toString(), path);
                    if (resultFile != null) {
                        Wini inifile = new Wini(resultFile);
                        productResult[0] = inifile.get("result", "chanpin");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });

//        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        cachedThreadPool.execute(new Runnable() {
            public void run() {
/**
 * @Author xiaweichao
 * @Description //TODO 获取人群包打分  * @Date 14:34 2020/7/23
 * @Param [generatePlansRequest]
 * @return com.ylyq.ylxx.model.ResponseData
 **/
                try {
                    log.info("获取人群包打分线程开始");
                    //获取标签打分值，并输出计划
//                if (StringUtils.isBlank(generatePlansRequest.getAge()) && StringUtils.isBlank(generatePlansRequest.getSex()) && null == generatePlansRequest.getBudget() && StringUtils.isBlank(generatePlansRequest.getArea())) {
                    List<Object> ylyqCoreTagList = ((List) redisUtil.lGet("ylyqCoreTag", 0, -1));
                    if (null != ylyqCoreTagList && !ylyqCoreTagList.isEmpty()) {
                        ylyqCoreTags[0] = (List<YlyqCoreTag>) ylyqCoreTagList.get(0);
                    }
                    if (ylyqCoreTags[0] == null || ylyqCoreTags[0].isEmpty()) {
                        ylyqCoreTags[0] = ylyqCoreTagMapper.selectList(null);
                        redisUtil.lSet("ylyqCoreTag", ylyqCoreTags[0]);
                    }
//                } else {
//                    QueryWrapper<YlyqCoreAge> agewrapper = new QueryWrapper<>();
//                    agewrapper.eq("age_flag", generatePlansRequest.getAge());
//                    List<YlyqCoreAge> ylyqCoreAges = ylyqCoreAgeMapper.selectList(agewrapper);
//                    QueryWrapper<YlyqCoreArea> areaswrapper = new QueryWrapper<>();
//                    areaswrapper.eq("area_flag", generatePlansRequest.getArea());
//                    List<YlyqCoreArea> ylyqCoreAreas = ylyqCoreAreaMapper.selectList(areaswrapper);
//                    QueryWrapper<YlyqCoreSex> sexswrapper = new QueryWrapper<>();
//                    sexswrapper.eq("sex_flag", generatePlansRequest.getSex());
//                    List<YlyqCoreSex> ylyqCoreSexes = ylyqCoreSexMapper.selectList(sexswrapper);
//
//
////人群包各维度得分 = 0.4 * 年龄得分 + 0.2 * 性别得分 + 0.4 * 地域得分
//                    for (YlyqCoreAge age : ylyqCoreAges) {
//                        for (YlyqCoreArea area : ylyqCoreAreas) {
//                            for (YlyqCoreSex sex : ylyqCoreSexes) {
//                                YlyqCoreTag tag = new YlyqCoreTag();
//                                tag.setPlanName(age.getAgeFlag() + "#" + area.getAreaFlag() + "#" + sex.getSexFlag());
//                                tag.setBd(0.4 * age.getBd() + 0.4 * area.getBd() + 0.2 * sex.getBd());
//                                tag.setDx(0.4 * age.getDx() + 0.4 * area.getDx() + 0.2 * sex.getDx());
//                                tag.setZpl(0.4 * age.getZpl() + 0.4 * area.getZpl() + 0.2 * sex.getZpl());
//                                tag.setXl(0.4 * age.getXl() + 0.4 * area.getXl() + 0.2 * sex.getXl());
//                                tag.setKk(0.4 * age.getKk() + 0.4 * area.getKk() + 0.2 * sex.getKk());
//                                tag.setCz(0.4 * age.getCz() + 0.4 * area.getCz() + 0.2 * sex.getCz());
//                                tag.setBhy(0.4 * age.getBhy() + 0.4 * area.getBhy() + 0.2 * sex.getBhy());
//                                tag.setX(0.4 * age.getX() + 0.4 * area.getX() + 0.2 * sex.getX());
//                                tag.setMs(0.4 * age.getMs() + 0.4 * area.getMs() + 0.2 * sex.getMs());
//                                tag.setSs(0.4 * age.getSs() + 0.4 * area.getSs() + 0.2 * sex.getSs());
//                                tag.setXiaoLv(0.4 * age.getXiaoLv() + 0.4 * area.getXiaoLv() + 0.2 * sex.getXiaoLv());
//                                tag.setRt(0.4 * age.getRt() + 0.4 * area.getRt() + 0.2 * sex.getRt());
//                                tag.setPb(0.4 * age.getPb() + 0.4 * area.getPb() + 0.2 * sex.getPb());
//                                tag.setHq(0.4 * age.getHq() + 0.4 * area.getHq() + 0.2 * sex.getHq());
//                                tag.setHeQun(0.4 * age.getHeQun() + 0.4 * area.getHeQun() + 0.2 * sex.getHeQun());
//                                tag.setHqxx(0.4 * age.getHqxx() + 0.4 * area.getHqxx() + 0.2 * sex.getHqxx());
//                                tag.setYq(0.4 * age.getYq() + 0.4 * area.getYq() + 0.2 * sex.getYq());
//                                ylyqCoreTags[0].add(tag);
//                            }
//                        }
//                    }
//                }
                    /**
                     * @Author xiaweichao
                     * @Description //TODO 根据人群包得分，产品得分，获取最终得分 * @Date 14:37 2020/7/23
                     * @Param [generatePlansRequest]
                     * @return com.ylyq.ylxx.model.ResponseData
                     **/

                    StringBuilder parmsPlan = new StringBuilder();
                    parmsPlan.append(ylyqCoreTags[0].size() + "~\n");
                    for (YlyqCoreTag temp : ylyqCoreTags[0]) {
                        parmsPlan.append(temp.getDx() + " " + temp.getZpl() + " " + temp.getXl() + " " + temp.getKk() + " " + temp.getCz() + " " + temp.getBhy() + " " + temp.getX() + " " + temp.getMs() + " " + temp.getSs() + " "
                                + temp.getXiaoLv() + " " + temp.getBd() + " " + temp.getRt() + " " + temp.getPb() + " " + temp.getHq() + " " + temp.getHeQun() + " " + temp.getHqxx() + " " + temp.getYq() + "\n");
                    }
                    parmsPlan.append("~\n");
                    planCoreResult[0] = parmsPlan.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                latch.countDown();
            }
        });

        cachedThreadPool.shutdown();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        log.info("两个子线程都执行完毕，继续执行主线程");

        StringBuilder sb = new StringBuilder();
        sb.append(planCoreResult[0]);
        sb.append(productResult[0] + "~");


//        String pathPlan = ResourceUtils.getURL("classpath:").getPath().replace("/target/classes", "") + "\\src\\main\\resources\\lingo\\lingosh.lng";
//        String pathPlan = System.getProperty("user.dir")+ "\\ylyq\\src\\main\\resources\\lingo\\lingosh.lng";
        String pathPlan = "lingo/lingosh.lng";

        File resultFilePlan = iLingoService.excuteLingo(sb.toString(), pathPlan);
        if (resultFilePlan != null) {

            //存储创意标题，供每次使用
            QueryWrapper<YlyqConvertUrl> urlQueryWrapper = new QueryWrapper<>();
            urlQueryWrapper.eq("covert_flag", generatePlansRequest.getShopFlag());
            urlQueryWrapper.select("covert_url");
            List<Object> convertUrls = iYlyqConvertUrlService.listObjs(urlQueryWrapper);

            List<String> cybtTitleName = new ArrayList<>();
            List<YlyqCreativeTitleV2> creativeTitleV2s = new ArrayList<>();
            for (String features : generatePlansRequest.getProductFeatures()) {
                for (String advantage : generatePlansRequest.getProductAdvantage()) {
                    for (Object converturl : convertUrls) {
                        cybtTitleName.add(generatePlansRequest.getBrandName() + generatePlansRequest.getProductName() + features + advantage + converturl);
                        YlyqCreativeTitleV2 ylyqCreativeTitleV2 = new YlyqCreativeTitleV2();
                        ylyqCreativeTitleV2.setAdvertiseId(generatePlansRequest.getAdvertiser_id());
                        ylyqCreativeTitleV2.setTitleName(generatePlansRequest.getBrandName() + generatePlansRequest.getProductName() + "，" + features + "，" + advantage + "，" + converturl);
                        ylyqCreativeTitleV2.setGroupName(groupName);
                        creativeTitleV2s.add(ylyqCreativeTitleV2);
                    }
                }
            }
//            iYlyqCreativeTitleV2Service.saveBatch(creativeTitleV2s);
            ylyqCreativeTitleV2Mapper.insertBatch(creativeTitleV2s);

            if (generatePlansRequest.getScrapBean() != null && !generatePlansRequest.getScrapBean().isEmpty()) {//需要处理碎片视频方式
                List<GeneratePlansRequest.CreativeScrapBean> scrapBeanList = generatePlansRequest.getScrapBean();
                List<YlyqCreativeVideoMaterial> ylyqCreativeVideoMaterialList = new ArrayList<>();
                for (GeneratePlansRequest.CreativeScrapBean scrapBean : scrapBeanList) {

                    if (scrapBean.getVideo_id() != null)
                        for (String temp : scrapBean.getVideo_id()) {
                            YlyqCreativeVideoMaterial ylyqCreativeVideoMaterial = new YlyqCreativeVideoMaterial();
                            ylyqCreativeVideoMaterial.setId(Tools.getUUID());
                            ylyqCreativeVideoMaterial.setGroupName(groupName);
                            ylyqCreativeVideoMaterial.setMaterialMode(scrapBean.getMaterial_mode());
                            ylyqCreativeVideoMaterial.setVideoId(temp);
                            ylyqCreativeVideoMaterial.setAdvertiseId(generatePlansRequest.getAdvertiser_id());
                            ylyqCreativeVideoMaterialList.add(ylyqCreativeVideoMaterial);
                        }
                }
                iYlyqCreativeVideoMaterialService.insertBatch(ylyqCreativeVideoMaterialList);
            }

            Wini ini = new Wini(resultFilePlan);
//            String jdm = "状态";
//            String solveStatus = ini.get(jdm, "solve_status");

            String jdm2 = "结果";

            List<ResultCore> resultCoresList = new ArrayList<>();
            for (int j = 1; j < ylyqCoreTags[0].size() + 1; j++) {
                resultCoresList.add(new ResultCore(j, Double.parseDouble(ini.get(jdm2, "人群编号-" + j))));
            }

            Collections.sort(resultCoresList, (o1, o2) -> new Double(o1.getCore() - o2.getCore()).intValue());
            if (resultCoresList != null && resultCoresList.size() > 0) {

                if (resultCoresList.size() > generatePlansRequest.getPlanCount()) {
                    resultCoresList = resultCoresList.subList(0, generatePlansRequest.getPlanCount());
                }

                Vector<ResultPlan> resultCoreTag = new Vector<>();
                try {
                    CountDownLatch cdl = new CountDownLatch(resultCoresList.size());
//                    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(resultCoresList.size());
                    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(resultCoresList.size()>3?3:resultCoresList.size());//   1
//                    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);//   1
                    for (int i = 0; i < resultCoresList.size(); i++) {
                        log.info("第" + i + "个开始");
//用线程池执行，加快效率
//FilterContextHandler.getAll()，因为子线程里没有主线程里的临时缓存值，如token等。所以要复制一份到子线程中，供子线程使用
                        CountRunnable runnable = new CountRunnable(cdl, FilterContextHandler.getAll(), groupName, ylyqCoreTags, resultCoresList, generatePlansRequest, resultCoreTag, i);
                        fixedThreadPool.execute(runnable);
                    }

                    fixedThreadPool.shutdown();
                    cdl.await();
                } catch (IndexOutOfBoundsException e) {

                }
                log.info("end======\n resultSize=====" + resultCoreTag.size() + "\nresult=====" + resultCoreTag.toString());


                redisUtil.set(String.valueOf(generatePlansRequest.getAdvertiser_id()), generatePlansRequest);

                return new ResponseData(ResponseData.Result.SUCCESS, resultCoreTag);
            }
        }

        return new ResponseData(ResponseData.Result.FAIL);
    }

    class CountRunnable implements Runnable {
        private CountDownLatch countDownLatch;
        private Map<String, Object> all;
        private List<YlyqCoreTag>[] ylyqCoreTags;
        private List<ResultCore> resultCoresList;
        private GeneratePlansRequest generatePlansRequest;
        private Vector<ResultPlan> resultCoreTag;
        private String groupName;
        private int i;

        public CountRunnable(CountDownLatch countDownLatch, Map<String, Object> all, String groupName, List<YlyqCoreTag>[] ylyqCoreTags, List<ResultCore> resultCoresList, GeneratePlansRequest generatePlansRequest, Vector<ResultPlan> resultCoreTag, int i) {
            this.countDownLatch = countDownLatch;
            this.all = all;
            this.groupName = groupName;
            this.ylyqCoreTags = ylyqCoreTags;
            this.resultCoresList = resultCoresList;
            this.generatePlansRequest = generatePlansRequest;
            this.resultCoreTag = resultCoreTag;
            this.i = i;

        }

        @Override
        public void run() {
            try {
                FilterContextHandler.setAll(all);
//                           tag.setPlanName(age.getAgeFlag() + "#" + area.getAreaFlag() + "#" + sex.getSexFlag());
                String planName = ylyqCoreTags[0].get(resultCoresList.get(i).getNum() - 1).getPlanName();
                String[] split = planName.split("#");
                if (split != null) {
                    /**
                     * @Author xiaweichao
                     * @Description //TODO 获取最优预算和成本 * @Date 14:38 2020/7/23
                     * @Param [generatePlansRequest]
                     * @return com.ylyq.ylxx.model.ResponseData
                     **/
                    //获取最优预算和预估广告成本
                    //1.先获取覆盖量 EstimateAudienceRequest
//                    EstimateAudienceRequest estimateAudienceRequest = new EstimateAudienceRequest();
//
//                    estimateAudienceRequest.setAdvertiser_id(generatePlansRequest.getAdvertiser_id());
//                    estimateAudienceRequest.setGender(split[2]);
//                    estimateAudienceRequest.setAge(new String[]{split[0]});
//
//                    estimateAudienceRequest.setDistrict("CITY");
                    //一共是一线、二线、三线、四线、其它。把结果存入redis，否则每次查找结果太慢
//                    List<YlyqCity> list = new ArrayList<>();
//                    String[] splitCity = split[1].split(",");
//                    for (String cityFlag : splitCity) {
//                        List<YlyqCity> temp = (List<YlyqCity>) ((List) redisUtil.lGet("ylyqCity-" + cityFlag, 0, -1).get(0));
//                        if (temp == null) {
//                            QueryWrapper<YlyqCity> queryWrapper = new QueryWrapper<>();
//                            queryWrapper.eq("city_flag", cityFlag);
//                            queryWrapper.select("city_id", "city_name");
//                            temp = iYlyqCityService.list(queryWrapper);
//                            redisUtil.lSet("ylyqCity-" + cityFlag, temp);
//                        }
//                        list.addAll(temp);
//                    }

                    List<ResultPlan.AreaBean> areaBeanList = new ArrayList<>();
                    if (generatePlansRequest.getIncludecityId() != null && generatePlansRequest.getIncludecityId().length > 0) {
                        QueryWrapper<YlyqAreaOceangine> areaqueryWrapper = new QueryWrapper<>();
                        areaqueryWrapper.in("id", generatePlansRequest.getIncludecityId()).or().in("parent_id", generatePlansRequest.getIncludecityId());
                        areaqueryWrapper.select("id", "city_name");

                        if (generatePlansRequest.getExcludecityId() != null && generatePlansRequest.getExcludecityId().length > 0) {
                            areaqueryWrapper.notIn("id", generatePlansRequest.getExcludecityId());
                            areaqueryWrapper.notIn("parent_id", generatePlansRequest.getExcludecityId());
                        }

                        List<YlyqAreaOceangine> listIncludeArea = iYlyqAreaOceangineService.list(areaqueryWrapper);

                        for (YlyqAreaOceangine temp : listIncludeArea) {
                            areaBeanList.add(new ResultPlan.AreaBean(Long.parseLong(temp.getId()), temp.getCityName()));
                        }

                    } else {
                        String[] splitCity = split[1].split(",");
                        QueryWrapper<YlyqCity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.in("city_flag", splitCity);
                        queryWrapper.select("city_id", "city_name");
                        if (generatePlansRequest.getExcludecityId() != null && generatePlansRequest.getExcludecityId().length > 0) {
                            queryWrapper.notIn("city_id", generatePlansRequest.getExcludecityId());
                            queryWrapper.notIn("city_parent_id", generatePlansRequest.getExcludecityId());
                        }
                        List<YlyqCity> listCity = iYlyqCityService.list(queryWrapper);
                        for (YlyqCity temp : listCity) {
                            areaBeanList.add(new ResultPlan.AreaBean(Long.parseLong(temp.getCityId()), temp.getCityName()));
                        }

//                        if (generatePlansRequest.getExcludecityId() != null && generatePlansRequest.getExcludecityId().length > 0) {
//                            QueryWrapper<YlyqAreaOceangine> areaExcludequeryWrapper = new QueryWrapper<>();
//                            areaExcludequeryWrapper.select("id", "city_name");
//                            areaExcludequeryWrapper.in("id", generatePlansRequest.getExcludecityId()).or().in("parent_id", generatePlansRequest.getExcludecityId());
//                            List<YlyqAreaOceangine> listExcludeArea = iYlyqAreaOceangineService.list(areaExcludequeryWrapper);
//                            for (YlyqAreaOceangine temp : listExcludeArea) {
//
//                                ResultPlan.AreaBean tempArea = new ResultPlan.AreaBean(Long.parseLong(temp.getId()), temp.getCityName());
//                                if(areaBeanList.contains(tempArea)){
//                                    areaBeanList.remove(tempArea);
//                                }
//                            }
//                        }

                    }

                    Long[] longscity = areaBeanList.stream().map(ResultPlan.AreaBean::getCityID).collect(Collectors.toList()).toArray(new Long[areaBeanList.size()]);
                    ResultPlan.AreaBean[] cityResult = areaBeanList.toArray(new ResultPlan.AreaBean[areaBeanList.size()]);


//                    estimateAudienceRequest.setCity(longscity);

//                    InterestKeywordRequest actionKeywordRequest = new InterestKeywordRequest();
//                    actionKeywordRequest.setAdvertiser_id(generatePlansRequest.getAdvertiser_id());
//                    actionKeywordRequest.setQuery_words(split[0]);
//                    OceanengineInterestKeyword interestKeyword = iOceanengineToolService.getInterestKeyword(actionKeywordRequest);
//                    estimateAudienceRequest.setInterest_tags(new Long[]{Long.parseLong(interestKeyword.getData().getList().get(0).getId())});
//                    OceanengineEstimateAudience oceanengineEstimateAudience = iOceanengineToolService.estimateAudience(estimateAudienceRequest);


                    //2.获取建议日预算和预期成本 SuggestBidRequest
                    SuggestBidRequest suggestBidRequest = new SuggestBidRequest();

                    suggestBidRequest.setPricing("PRICING_OCPM");//暂时默认固定这个出价方式

                    suggestBidRequest.setAdvertiser_id(generatePlansRequest.getAdvertiser_id());
                    suggestBidRequest.setGender(split[2]);
                    suggestBidRequest.setAge(split[0].split(","));

                    suggestBidRequest.setDistrict("CITY");

                    suggestBidRequest.setCity(longscity);
                    suggestBidRequest.setConvert_id(generatePlansRequest.getCovertId());

//                    suggestBidRequest.setInterest_tags(new Long[]{Long.parseLong(interestKeyword.getData().getList().get(0).getId())});

                    OceanengineSuggestBid oceanengineSuggestBid = iOceanengineToolService.suggestBid(suggestBidRequest);
                    //3.调用lingo获取最优预算和成本
                    StringBuilder parmsBudgt = new StringBuilder();
                    if (null != oceanengineSuggestBid.getData().getBid_high_50())
                        parmsBudgt.append(oceanengineSuggestBid.getData().getBid_high_50() + "~\n");
                    parmsBudgt.append(generatePlansRequest.getPriceForm() + "~\n");
                    parmsBudgt.append("4~\n");
                    QueryWrapper<YlyqTypeProduct> queryWrapper = new QueryWrapper<>();
                    queryWrapper.select("product_flag");
                    queryWrapper.eq("product_name", generatePlansRequest.getProductName());
                    List<Object> productNames = iYlyqTypeProductService.listObjs(queryWrapper);
                    if (productNames != null && !productNames.isEmpty())
                        parmsBudgt.append(productNames.get(0).toString() + "~\n");

                    QueryWrapper<YlyqBudget> queryWrapperBudget = new QueryWrapper<>();
                    queryWrapperBudget.eq("advertise_id", generatePlansRequest.getAdvertiser_id());
                    YlyqBudget ylyqBudget = iYlyqBudgetService.getOne(queryWrapperBudget);
                    if (ylyqBudget.getBudgetModeDay().equals("BUDGET_MODE_INFINITE")) {
                        parmsBudgt.append("999999999");
                    } else {
                        parmsBudgt.append(ylyqBudget.getBudgetDay());
                    }

                    String plan = "OCPM_" + Tools.getCurrentDate("yyyyMMdd_HH_mm") + "_" + (i + 1);//计划的名称，也对应执行lingobid的输出文件的取名
//                    String pathBid = ResourceUtils.getURL("classpath:").getPath().replace("/target/classes", "") + "\\src\\main\\resources\\lingo\\lingobid.lng";
//                    String pathBid = System.getProperty("user.dir")+ "\\ylyq\\src\\main\\resources\\lingo\\lingobid.lng";;
                    String pathBid = null;
                    if (null != generatePlansRequest.getShopFlag() && generatePlansRequest.getShopFlag() == 0) {//表单还是鲁班标识。0鲁班，1表单
                        pathBid = "lingo/lingobidLuban.lng";
                    } else {
                        pathBid = "lingo/lingobid.lng";
                    }
                    File resultFileBid = iLingoService.excuteLingo(parmsBudgt.toString(), pathBid, plan);

                    // PythonUtil.execPython("D:\\package\\NewPlanModel\\BuildMain.py",planInputFile.getAbsolutePath(),bidInputFile.getAbsolutePath(),creativeInputFile.getAbsolutePath());

                    if (resultFileBid != null) {
                        Wini iniBid = new Wini(resultFileBid);
                        //这些是计划相关的
                        String[] chujiaArray = iniBid.get("jieguo", "chujia").split(",");//会有三个，每次取的时候，按下标取
//                        double chujia = Double.parseDouble(iniBid.get("jieguo", "chujia"));
                        double rys = Double.parseDouble(iniBid.get("jieguo", "rys"));

                        //以下是创意相关的
                        ResultPlan.CreativeBean creativeBean = new ResultPlan.CreativeBean();
                        creativeBean.setInventory_type(generatePlansRequest.getInventory_type());
                        //创意素材
                        if (generatePlansRequest.getScrapBean() == null || generatePlansRequest.getScrapBean().isEmpty()) {//不需要处理视频方式
                            creativeBean.setImage_list(generatePlansRequest.getImage_list());
                        } else {//需要处理视频方式
                            List<CreateCreativeRequest.ImageListBean> image_list = new ArrayList<>();
                            List<GeneratePlansRequest.CreativeScrapBean> scrapBeanList = generatePlansRequest.getScrapBean();
                            for (GeneratePlansRequest.CreativeScrapBean scrapBeanTemp : scrapBeanList) {
                                switch (scrapBeanTemp.getMaterial_mode()) {
                                    case "CREATIVE_IMAGE_MODE_VIDEO":
                                    case "CREATIVE_IMAGE_MODE_VIDEO_VERTICAL":
                                    case "CREATIVE_IMAGE_MODE_UNION_SPLASH_VIDEO":
                                        QueryWrapper<YlyqCreativeVideoMaterial> videoMaterialQueryWrapper = new QueryWrapper<>();
                                        videoMaterialQueryWrapper.eq("advertise_id", generatePlansRequest.getAdvertiser_id());
                                        videoMaterialQueryWrapper.eq("group_name", groupName);
                                        videoMaterialQueryWrapper.eq("material_mode", scrapBeanTemp.getMaterial_mode());
                                        videoMaterialQueryWrapper.select("id","video_id", "material_mode");
                                        videoMaterialQueryWrapper.orderByAsc("RAND()");//随机选视频
//                                        List<YlyqCreativeVideoMaterial> videoMaterial = iYlyqCreativeVideoMaterialService.list(videoMaterialQueryWrapper);
//
//                                        //需要用分页优化，还有在模型投放时新增的时候，也是
//                                        int videoMaterialsize = videoMaterial.size() > 3 ? 3 : videoMaterial.size();
//                                        if (videoMaterialsize > 0) {
//                                            for (int j = 0; j < videoMaterialsize; j++) {
//                                                CreateCreativeRequest.ImageListBean creativeListBean = new CreateCreativeRequest.ImageListBean();
//                                                creativeListBean.setVideo_id(videoMaterial.get(j).getVideoId());
//                                                creativeListBean.setImage_id(scrapBeanTemp.getImage_id());
////                                                    creativeListBean.setImage_mode(videoMaterial.get(j).getMaterialMode());
//                                                creativeListBean.setImage_mode(scrapBeanTemp.getMaterial_mode());
//                                                image_list.add(creativeListBean);
//                                            }
//                                            QueryWrapper<YlyqCreativeVideoMaterial> removeQueryWrapper = new QueryWrapper<>();
//                                            removeQueryWrapper.eq("advertise_id", generatePlansRequest.getAdvertiser_id());
//                                            removeQueryWrapper.eq("group_name", groupName);
//                                            removeQueryWrapper.eq("material_mode", scrapBeanTemp.getMaterial_mode());
//                                            removeQueryWrapper.in("video_id", image_list.stream().map(CreateCreativeRequest.ImageListBean::getVideo_id).collect(Collectors.toSet()));
//                                            iYlyqCreativeVideoMaterialService.remove(removeQueryWrapper);
//                                        }

                                        List<YlyqCreativeVideoMaterial> videoMaterial = iYlyqCreativeVideoMaterialService.page(new Page<>(0, 3), videoMaterialQueryWrapper).getRecords();
                                        if (!videoMaterial.isEmpty()&&videoMaterial.size() > 0) {
                                            for (int j = 0; j < videoMaterial.size(); j++) {
                                                CreateCreativeRequest.ImageListBean creativeListBean = new CreateCreativeRequest.ImageListBean();
                                                creativeListBean.setVideo_id(videoMaterial.get(j).getVideoId());
                                                creativeListBean.setImage_id(scrapBeanTemp.getImage_id());
//                                                    creativeListBean.setImage_mode(videoMaterial.get(j).getMaterialMode());
                                                creativeListBean.setImage_mode(scrapBeanTemp.getMaterial_mode());
                                                image_list.add(creativeListBean);
                                            }

                                            iYlyqCreativeVideoMaterialService.removeByIds(videoMaterial.stream().map(YlyqCreativeVideoMaterial::getId).collect(Collectors.toList()));
                                        }


                                        break;
                                    default:
                                        CreateCreativeRequest.ImageListBean creativeListBean = new CreateCreativeRequest.ImageListBean();
                                        creativeListBean.setImage_ids(scrapBeanTemp.getImage_ids().toArray(new String[scrapBeanTemp.getImage_ids().size()]));
                                        creativeListBean.setImage_mode(scrapBeanTemp.getMaterial_mode());
                                        image_list.add(creativeListBean);
                                        break;
                                }
                            }
                            if (image_list == null || image_list.isEmpty()) {//如果素材不够了，就用第一个创意素材
                                if (!resultCoreTag.isEmpty()) {
                                    creativeBean.setImage_list(resultCoreTag.get(0).getCreativeBean().getImage_list());
                                }
                            } else {
                                creativeBean.setImage_list(image_list);
                            }
                        }
                        //创意标题
                        String cybt = iniBid.get("jieguo", "cybt");
                        if (StringUtils.isNotBlank(cybt)) {

                            List<CreateCreativeRequest.TitleListBean> creativeTitleList = new ArrayList<>();

                            QueryWrapper<YlyqCreativeTitleV2> titleV2QueryWrapper = new QueryWrapper<>();
                            titleV2QueryWrapper.eq("advertise_id", generatePlansRequest.getAdvertiser_id());
                            titleV2QueryWrapper.eq("group_name", groupName);
                            titleV2QueryWrapper.select("id","title_name");
                            titleV2QueryWrapper.orderByAsc("RAND()");//随机选标题
//                            List<YlyqCreativeTitleV2> objectsTitles = iYlyqCreativeTitleV2Service.list(titleV2QueryWrapper);
//                            //需要用分页优化，还有在模型投放时新增的时候，也是
//                            int titlesSize = objectsTitles.size() > 5 ? 5 : objectsTitles.size();
//                            if (titlesSize > 0) {
//                                for (int j = 0; j < titlesSize; j++) {
//                                    creativeTitleList.add(new CreateCreativeRequest.TitleListBean(objectsTitles.get(j).getTitleName(), null, null));
//                                }
//                                creativeBean.setCybt(creativeTitleList);
//
//                                QueryWrapper<YlyqCreativeTitleV2> removeQueryWrapper = new QueryWrapper<>();
//                                removeQueryWrapper.eq("advertise_id", generatePlansRequest.getAdvertiser_id());
//                                removeQueryWrapper.eq("group_name", groupName);
////                                removeQueryWrapper.in("title_name", objectsTitles.subList(0, titlesSize));
//                                removeQueryWrapper.in("title_name", creativeTitleList.stream().map(CreateCreativeRequest.TitleListBean::getTitle).collect(Collectors.toList()));
//                                iYlyqCreativeTitleV2Service.remove(removeQueryWrapper);
//                            }

                            List<YlyqCreativeTitleV2> objectsTitles = iYlyqCreativeTitleV2Service.page(new Page<>(0, 5), titleV2QueryWrapper).getRecords();
                            if(objectsTitles.size() < 5){
                                if (!resultCoreTag.isEmpty()) {
                                    creativeBean.setCybt(resultCoreTag.get(0).getCreativeBean().getCybt());
                                }
                            }else{
                                if (!objectsTitles.isEmpty()&&objectsTitles.size() > 0) {
                                    for (int j = 0; j < objectsTitles.size(); j++) {
                                        creativeTitleList.add(new CreateCreativeRequest.TitleListBean(objectsTitles.get(j).getTitleName(), null, null));
                                    }
                                    creativeBean.setCybt(creativeTitleList);

                                    iYlyqCreativeTitleV2Service.removeByIds(objectsTitles.stream().map(YlyqCreativeTitleV2::getId).collect(Collectors.toList()));
                                }
                            }
                        }


                        creativeBean.setCyfl(Long.parseLong(generatePlansRequest.getCategory_id()));

                        int ppzy = Integer.parseInt(iniBid.get("jieguo", "ppzy"));
                        switch (ppzy) {
                            case 0:
                                creativeBean.setPpzy(null);
                                break;
                            case 1://开启品牌主页，需要再填上推广抖音号
                                break;
                            default:
                                creativeBean.setPpzy(null);//品牌主页的推广抖音号
                                break;
                        }


                        //是否支持自动生成素材。视频个数大于9或图片素材大于11不能支持
                        int imageSize=0;
                        int videoSize=0;
                        for (CreateCreativeRequest.ImageListBean imageBean : creativeBean.getImage_list()) {

                            if (imageBean.getImage_mode().equals("CREATIVE_IMAGE_MODE_LARGE") || imageBean.getImage_mode().equals("CREATIVE_IMAGE_MODE_SMALL") ||
                                    imageBean.getImage_mode().equals("CREATIVE_IMAGE_MODE_GROUP") || imageBean.getImage_mode().equals("CREATIVE_IMAGE_MODE_LARGE_VERTICAL")) {
                                imageSize++;
                            } else if (imageBean.getImage_mode().equals("CREATIVE_IMAGE_MODE_VIDEO") || imageBean.getImage_mode().equals("CREATIVE_IMAGE_MODE_VIDEO_VERTICAL")) {
                                videoSize++;
                            }
                        }

                        int zdscspsc = Integer.parseInt(iniBid.get("jieguo", "zdscspsc"));
                        creativeBean.setZdscspsc(zdscspsc);

                        if (imageSize<12&&videoSize<10) {
                            creativeBean.setCreative_auto_generate_switch(1);
                        }else {
                            creativeBean.setCreative_auto_generate_switch(0);
                        }

                        int zycyysjh = Integer.parseInt(iniBid.get("jieguo", "zycyysjh"));
                        creativeBean.setZycyysjh(zycyysjh);
                        int ggpl = Integer.parseInt(iniBid.get("jieguo", "ggpl"));
                        switch (ggpl) {
                            case 0:
                                creativeBean.setGgpl(1);
                                break;
                            case 1:
                                creativeBean.setGgpl(0);
                                break;
                        }

                        int cyzx = Integer.parseInt(iniBid.get("jieguo", "cyzx"));
                        switch (cyzx) {
                            case 0:
                                creativeBean.setCyzx("CREATIVE_DISPLAY_MODE_CTR");
                                break;
                            case 1:
                                creativeBean.setCyzx("CREATIVE_DISPLAY_MODE_RANDOM");
                                break;
                        }

                        int cyfs = Integer.parseInt(iniBid.get("jieguo", "cyfs"));
//                        创意类型，当值为"STATIC_ASSEMBLE"表示程序化创意，其他情况不传字段
                        switch (cyfs) {
                            case 0:
                                creativeBean.setCyfs("STATIC_ASSEMBLE");
                                break;
                            default:
                                break;
                        }
                        //行为兴趣
                        String interest_action_mode = null;
                        int xwxq = Integer.parseInt(iniBid.get("jieguo", "xwxq"));
                        switch (xwxq) {//"UNLIMITED","CUSTOM","RECOMMEND"
                            case 0:
                                interest_action_mode = "UNLIMITED";
                                break;
                            case 1:
                                interest_action_mode = "RECOMMEND";
                                break;
                            case 2:
                                interest_action_mode = "CUSTOM";
                                break;
                            default:
                                break;
                        }
                        //过滤已转化用户
                        //NO_EXCLUDE	不过滤	AD	广告计划	CAMPAIGN	广告组	ADVERTISER	广告账户	APP	APP	CUSTOMER	公司账户
                        String hide_if_converted = null;
                        int glyzhyh = Integer.parseInt(iniBid.get("jieguo", "glyzhyh"));
                        switch (glyzhyh) {//不限	广告计划	广告组	广告账户	公司账户
                            //                            0	1	2	3	4
                            case 0:
                                hide_if_converted = "NO_EXCLUDE";
                                break;
                            case 1:
                                hide_if_converted = "AD";
                                break;
                            case 2:
                                hide_if_converted = "CAMPAIGN";
                                break;
                            case 3:
                                hide_if_converted = "ADVERTISER";
                                break;
                            case 4:
                                hide_if_converted = "CUSTOMER";
                                break;
                            default:
                                break;
                        }
                        String xdhz = iniBid.get("jieguo", "xdhz");
                        if (StringUtils.isNotBlank(xdhz)) {
                            QueryWrapper<YlyqCreativeAciton> creativeAcitonQueryWrapper = new QueryWrapper<>();
                            creativeAcitonQueryWrapper.eq("action_id", xdhz);
                            YlyqCreativeAciton one = iYlyqCreativeAcitonService.getOne(creativeAcitonQueryWrapper);
                            creativeBean.setXdhz(one.getActionName());
                        }

                        String cybq = iniBid.get("jieguo", "cybq");
                        if (StringUtils.isNotBlank(cybq)) {
                            QueryWrapper<YlyqCreativeTag> creativeTagQueryWrapper = new QueryWrapper<>();
                            creativeTagQueryWrapper.select("tag_name");
                            creativeTagQueryWrapper.in("tag_id", cybq.split(","));
                            List<Object> creativeTags = iYlyqCreativeTagService.listObjs(creativeTagQueryWrapper);
                            creativeBean.setCybq((List<String>) (List) creativeTags);
                        }

//                        String ly = iniBid.get("jieguo", "ly");
//                        if(StringUtils.isNotBlank(ly)){
//                            QueryWrapper<YlyqCreativeSource> creativeSourceQueryWrapper=new QueryWrapper<>();
//                            creativeSourceQueryWrapper.select("source_name");
//                            creativeSourceQueryWrapper.in("source_id",ly.split(","));
//                            List<Object> creativeSource = iYlyqCreativeSourceService.listObjs(creativeSourceQueryWrapper);
//                            creativeBean.setLy(creativeSource);
//                        }
                        creativeBean.setLy(generatePlansRequest.getCompanyName());


                        if (null != generatePlansRequest.getShopFlag() && generatePlansRequest.getShopFlag() == 0) {//表单还是鲁班标识。0鲁班，1表单
                            String delivery_range = null;
                            String tffw = iniBid.get("jieguo", "tffw");
                            switch (tffw) {
//                                默认	穿山甲	智选通投
//                                0	1	2
                                case "0":
                                    delivery_range = "DEFAULT";
                                    break;
                                case "1":
                                    delivery_range = "UNION";
                                    break;
                                case "2":
                                    delivery_range = "UNIVERSAL";
                                    break;
                            }


                            creativeBean.setGgwz(1);//优选广告位，0表示不使用优选，1表示使用，使用优选广告位的时候默认忽略inventory_type字段。 默认值: 0 允许值: 0, 1

                            log.info("addResultPlan================>>>>>>" + i);
//                            addResultPlan(resultCoreTag, new ResultPlan(groupName, plan, generatePlansRequest.getExternal_url(), delivery_range, hide_if_converted, interest_action_mode, split[0], cityResult, split[2],
//                                    Double.parseDouble(chujiaArray[i]), rys, oceanengineSuggestBid.getData().getBid_high_50(), null,
//                                    generatePlansRequest.getProductName(), generatePlansRequest.getCovertId(), null, generatePlansRequest.getCompanyName(),
//                                    generatePlansRequest.getCompanyHead(), generatePlansRequest.getPriceForm(), generatePlansRequest.getChooseUrl(), generatePlansRequest.getChooseCodeUrl(), creativeBean));
                            resultCoreTag.add(new ResultPlan(groupName, plan, generatePlansRequest.getExternal_url(), delivery_range, hide_if_converted, interest_action_mode, split[0], cityResult, split[2],
                                    Double.parseDouble(chujiaArray[i%3]), rys, oceanengineSuggestBid.getData().getBid_high_50(), null,
                                    generatePlansRequest.getProductName(), generatePlansRequest.getCovertId(), null, generatePlansRequest.getCompanyName(),
                                    generatePlansRequest.getCompanyHead(), generatePlansRequest.getPriceForm(), generatePlansRequest.getChooseUrl(), generatePlansRequest.getChooseCodeUrl(), creativeBean));
                        } else {

                            int ggwz = Integer.parseInt(iniBid.get("jieguo", "ggwz"));
                            switch (ggwz) {
                                case 0:
                                    creativeBean.setGgwz(1);
                                    break;
                                case 1:
                                    creativeBean.setGgwz(0);
                                    break;
                            }

                            log.info("addResultPlan================>>>>>>" + i);
//                            addResultPlan(resultCoreTag, new ResultPlan(groupName, plan, generatePlansRequest.getExternal_url(), "DEFAULT", hide_if_converted, interest_action_mode, split[0], cityResult, split[2],
//                                    Double.parseDouble(chujiaArray[i]), rys, oceanengineSuggestBid.getData().getBid_high_50(), null,
//                                    generatePlansRequest.getProductName(), generatePlansRequest.getCovertId(), null, generatePlansRequest.getCompanyName(),
//                                    generatePlansRequest.getCompanyHead(), generatePlansRequest.getPriceForm(), generatePlansRequest.getChooseUrl(), generatePlansRequest.getChooseCodeUrl(), creativeBean));
                            resultCoreTag.add(new ResultPlan(groupName, plan, generatePlansRequest.getExternal_url(), "DEFAULT", hide_if_converted, interest_action_mode, split[0], cityResult, split[2],
                                    Double.parseDouble(chujiaArray[i%3]), rys, oceanengineSuggestBid.getData().getBid_high_50(), null,
                                    generatePlansRequest.getProductName(), generatePlansRequest.getCovertId(), null, generatePlansRequest.getCompanyName(),
                                    generatePlansRequest.getCompanyHead(), generatePlansRequest.getPriceForm(), generatePlansRequest.getChooseUrl(), generatePlansRequest.getChooseCodeUrl(), creativeBean));
                        }

                    }
                }

                /*** 每次减少一个容量*/
                log.info("thread counts = " + (countDownLatch.getCount()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        }
    }
}
